<template>
  <div class="editor-box">
    <div style="border: 1px solid #ccc; margin-top: 10px; z-index: 99">
      <Toolbar
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
        style="border-bottom: 1px solid #ccc"
      />
      <Editor
        :defaultConfig="editorConfig"
        :mode="mode"
        v-model="valueHtml"
        style="height: 600px; overflow-y: hidden"
        @onCreated="handleCreated"
        @onChange="handleChange"
        @onDestroyed="handleDestroyed"
        @onFocus="handleFocus"
        @onBlur="handleBlur"
        @customAlert="customAlert"
        @customPaste="customPaste"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"

import { ElMessage } from "element-plus";
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import type { InsertFnType } from "@wangeditor/editor-for-vue";
import { commonRequest } from "/@/api/common";
import moment from "moment";
const emit = defineEmits(["change-data"]);

const mode = "default";
// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("");

interface props {
  url?: string;
}
const props = withDefaults(defineProps<props>(), {});

// 异步获取内容
watch(
  () => props.url,
  async () => {
    if (props.url) {
      const res: any = await commonRequest({ url: props.url });
      valueHtml.value = res;
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

const toolbarConfig = {};
const editorConfig: any = { placeholder: "请输入内容...", MENU_CONF: {} };

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;

  editor.destroy();
});

// 编辑器回调函数
const handleCreated = (editor: any) => {
  console.log("created", editor);
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const handleChange = (editor: any) => {
  // console.log("change:", editor.getHtml());
  emit("change-data", editor.getHtml());
};
const handleDestroyed = (editor: any) => {
  console.log("destroyed", editor);
};
const handleFocus = (editor: any) => {
  console.log("focus", editor);
};
const handleBlur = (editor: any) => {
  console.log("blur", editor);
};
const customAlert = (info: any, type: any) => {
  alert(`【自定义提示】${type} - ${info}`);
};
const customPaste = (editor: any, event: any, callback: any) => {
  // console.log("ClipboardEvent 粘贴事件对象", event);

  // const html = event.clipboardData.getData("text/html"); // 获取粘贴的 html
  const text = event.clipboardData.getData("text/plain"); // 获取粘贴的纯文本
  // const rtf = event.clipboardData.getData("text/rtf"); // 获取 rtf 数据（如从 word wsp 复制粘贴）

  // 自定义插入内容
  editor.insertText(text);

  // 返回值（注意，vue 事件的返回值，不能用 return）
  callback(false); // 返回 false ，阻止默认粘贴行为
  // callback(true) // 返回 true ，继续默认的粘贴行为
};

editorConfig.MENU_CONF["uploadImage"] = {
  // 自定义上传图片
  // async customUpload(file: File, insertFn: InsertFnType) {
  //   // TS 语法
  //   console.log(file);
  //   const res = await onFileUpload(
  //     file,
  //     "solution_plan/" + "image/" + moment().format("YYYY-MM-DD hh:mm:ss")
  //   );
  //   if (res.status === "success") {
  //     // file 即选中的文件
  //     // 自己实现上传，并得到图片 url alt href
  //     // 最后插入图片
  //     insertFn(res.url as string, res.name as string, "");
  //   } else {
  //     ElMessage({
  //       message: "上传失败！请重新上传！",
  //       type: "error",
  //     });
  //   }
  // },
};

editorConfig.MENU_CONF["uploadVideo"] = {
  // 自定义上传
  // async customUpload(file: File, insertFn: InsertFnType) {
  //   // TS 语法
  //   // file 即选中的文件
  //   // 自己实现上传，并得到视频 url poster
  //   // 最后插入视频
  //   console.log(file);
  //   // const res = await onFileUpload(
  //   //   file,
  //   //   "solution_plan/" + "video/" + moment().format("YYYY-MM-DD hh:mm:ss")
  //   // );
  //   console.log(res, "1111");
  //   if (res.status === "success") {
  //     insertFn(res.url as string, res.name as string, "");
  //   } else {
  //     ElMessage({
  //       message: "上传失败！请重新上传！",
  //       type: "error",
  //     });
  //   }
  // },
};

const insertText = () => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.insertText("hello world");
};

const printHtml = () => {
  const editor = editorRef.value;
  if (editor == null) return;
  console.log(editor.getHtml());
};

const disable = () => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.disable();
};
</script>
<style scoped lang="less">
.editor-box {
  z-index: 9999;
  &:deep(ol) {
    list-style-type: decimal !important;
  }
  &:deep(ul) {
    list-style-type: disc !important;
  }
  &:deep(h1) {
    font-size: 2em;
    font-weight: bold;
  }
  &:deep(h2) {
    font-size: 1.5em;
    font-weight: bold;
  }
  &:deep(h3) {
    font-size: 1.17em;
    font-weight: bold;
  }
  &:deep(h4) {
    font-weight: bold;
  }
  &:deep(h5) {
    font-size: 0.83em;
    font-weight: bold;
  }
}
</style>
